/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is What's That Preference?.
 *
 * The Initial Developer of the Original Code is
 * George Bradt.
 * Portions created by the Initial Developer are Copyright (C) 2011
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var WhatsThatPref = {

    myFrame: null,
    myDeck: null,
    myPanel: null,

	// When our "MozillaZine reference" menuitem is clicked.

    mozillaZineReference: function(aPrefName) {
        if ( document.getElementById("wtp-mitemResults").getAttribute("checked") == "false" ) {
            // Results to tab.
            this.openLink("http://kb.mozillazine.org/" + aPrefName);
        }
        else {
            // Results to panel.
            this.loadFrame("http://kb.mozillazine.org/" + aPrefName);
        }
    },

	// When our "MozillaZine group reference" menuitem is clicked.

    mozillaZineGroupReference: function(aPrefName) {
        let group = aPrefName.split(".")[0] + ".";
        let groupCapitalized = group.charAt(0).toUpperCase() + group.slice(1);

        if ( document.getElementById("wtp-mitemResults").getAttribute("checked") == "false" ) {
            this.openLink("http://kb.mozillazine.org/About:config_entries#" + groupCapitalized);
        }
        else {
            this.loadFrame("http://kb.mozillazine.org/About:config_entries#" + groupCapitalized);
        }
    },

	// When our "Web search" menuitem is clicked.

    webSearch: function(aPrefName) {
        this.openLink('http://www.google.com/search?q="' + aPrefName + '"');
    },

    // Workaround for bug 15232.

    toggleResultsState: function(aMenuitem) {
        if ( aMenuitem.getAttribute("checked") === "true" ) {
            aMenuitem.setAttribute("checked", "false");
        }
        else {
            aMenuitem.setAttribute("checked", "true");
        }
    },

    // Open page in new tab.

	openLink: function(aUrl) {
		let wm = Components.classes["@mozilla.org/appshell/window-mediator;1"].
                getService(Components.interfaces.nsIWindowMediator);
        let win = wm.getMostRecentWindow("navigator:browser");

        let tabbrowser = win.gBrowser;
        let numTabs =  tabbrowser.browsers.length;
        let currentBrowser;
        let blankIndex = -1;

        // Use a blank if possible.
        for ( var i = 0; i < numTabs; i++ ) {
            currentBrowser = tabbrowser.getBrowserAtIndex(i);

            if ( currentBrowser.currentURI.spec == "about:blank" && blankIndex < 0 ) {
                // Use the first blank tab if URL not found.
                blankIndex = i;
                break;
            }
        }

        if ( blankIndex > -1 ) {
            // Use blank.
            tabbrowser.getBrowserAtIndex(blankIndex).loadURI(aUrl);
            tabbrowser.selectedTab = tabbrowser.tabContainer.childNodes[blankIndex];
        }
        else {
            let tab = tabbrowser.addTab(aUrl);
            tabbrowser.selectedTab = tab;
        }
	},

	// Load page into iframe.

    loadFrame: function(aUrl) {
        if ( !this.myPanel ) {
            this.myPanel = document.getElementById("wtp-panel");
        }

        if ( !this.myDeck ) {
            this.myDeck = document.getElementById("wtp-deck");
        }

        if ( !this.myFrame ) {
            this.myFrame = document.getElementById("wtp-frame");
            this.myFrame.webNavigation.allowAuth = false;
            this.myFrame.webNavigation.allowImages = false;
            this.myFrame.webNavigation.allowJavascript = false;
            this.myFrame.webNavigation.allowMetaRedirects = false;
            this.myFrame.webNavigation.allowPlugins = false;
            this.myFrame.webNavigation.allowSubframes = false;
        }

        // Show loading message.
        this.myDeck.selectedIndex = 0;
        this.myPanel.openPopupAtScreen(300, 200, false);

        this.myFrame.addEventListener("load", WhatsThatPref.onPageLoad, true);
        this.myFrame.webNavigation.loadURI(aUrl,
                                           Components.interfaces.nsIWebNavigation.LOAD_FLAGS_BYPASS_CACHE,
                                           null, null, null
                                          );
    },

	// Open page in the panel.

	onPageLoad: function() {
        // iframe is child of panel.
        WhatsThatPref.myDeck.selectedIndex = 1;
	},

	// Remove event listener when panel is closed.

	onPanelClosed: function() {
        if ( this.myFrame ) {
            this.myFrame.removeEventListener("load", WhatsThatPref.onPageLoad, true);
        }
	},

	// Debug messages to console.

	debug: function(aMsg) {
		window.setTimeout(function() { throw new Error("[debug] " + aMsg); }, 0);
	}
};